package cmd

import (
	"fmt"
	"github.com/kevinlisr/install-levault/conf"
	"github.com/kevinlisr/install-levault/service"
	"github.com/kevinlisr/install-levault/vari"
	"github.com/spf13/cobra"
)

// Two-level command
var installCmd = &cobra.Command{
	Use:   "install",
	Short: "install middlewares",
	Long: `Install Middlewares
           use: install middlewares
                install middlewares -f /data/middleware/config.toml`,
	RunE: func(cmd *cobra.Command, args []string) error {
		vari.Logger.Info("Install middleware ...")
		return nil
	},
}

// Three-level command
var itcopCmd = &cobra.Command{
	Use:   "middleware",
	Short: "安装中间件",
	Long:  `安装中间件`,
	RunE: func(cmd *cobra.Command, args []string) error {
		// 初始化全局变量
		if err := loadGlobalConfig(ConfType, Format); err != nil {
			return fmt.Errorf("LoadGlobalConfig failed %s\n", ConfFile)
		}
		conf := conf.C()

		vari.Logger.Info("Install itcop...")

		pkgs := []string{conf.Packages.Jdk, conf.Packages.Dm, conf.Packages.Minio, conf.Packages.Nacos,
			conf.Packages.Nebulagraph, conf.Packages.Redis, conf.Packages.Rocketmq,
			conf.Packages.Openresty, conf.Packages.Erlang, conf.Packages.Socat, conf.Packages.Rabbitmq,
		}

		fmt.Println("+++++++++++++", pkgs)
		installer := service.NewInstaller()
		err := installer.DeployMiddle(pkgs, conf)
		if err != nil {
			vari.Logger.Error("DeployMiddle Failed" + err.Error())
			return err
		}
		vari.Logger.Info("Deploy Middleware Success!")
		return nil
	},
}

func init() {
	RootCmd.AddCommand(installCmd)
	installCmd.AddCommand(itcopCmd)
	itcopCmd.PersistentFlags().StringVarP(&ConfType, "config-type", "t", "file", "the service config type [file/env/etcd], install middleware -t file ")
	itcopCmd.PersistentFlags().StringVarP(&ConfFile, "config-file", "f", "etc/config.yaml", "the service config from file, install middleware -f /root/config.yaml")
	itcopCmd.PersistentFlags().StringVarP(&Format, "format", "m", "yaml", "dm download -m yaml")
}
